<template>
  <el-dialog v-model="dialogVisible" title="人员选择" width="80%" @close="cancle">
    <el-row>
      <!-- 左侧部门树 -->
      <el-col :span="4" :xs="24">
        <ContentWrap class="h-1/1">
          <DeptTree @node-click="handleDeptNodeClick" @switch-statue="switchStatueChange" />
        </ContentWrap>
      </el-col>
      <el-col :span="16" :xs="24">
        <ContentWrap>
<!--          <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">-->
<!--            <el-form-item label="员工姓名" prop="nickname">-->
<!--              <el-input-->
<!--v-model="queryParams.nickname" placeholder="请输入" clearable :suffix-icon="Search"-->
<!--                @keydown.enter.prevent @keyup.enter="handleQuery" class="!w-240px" />-->
<!--            </el-form-item>-->
<!--          </el-form>-->
          <advanced-search
            :heightSearch="heightSearch" :params="singleParams" @heigth-search-value="heigthSearchValue"
            @single-search='singleSearch' @reset-table="resetTable" />
        </ContentWrap>
        <ContentWrap>

          <el-table
          ref="multipleTable"
height="400px" :data="list" :header-cell-style="{ 'background': '#F5F4FD', 'color': '#333' }" border
            style="width: 100%" @current-change="handleCurrentChange" @selection-change="handleSelectionChange"
            @select="selectChange">
            <el-table-column type="selection" width="55" v-if="select == 'multiple'" />
            <el-table-column label="姓名" align="center" prop="nickname" :show-overflow-tooltip="true" />
            <el-table-column label="工号" align="center" prop="jobNumber" :show-overflow-tooltip="true" />
            <el-table-column label="职位" align="center" prop="titleName" :show-overflow-tooltip="true" />
            <el-table-column label="工作性质" align="center" prop="employeeType" width="120" />
            <el-table-column label="员工状态" align="center" prop="employeeStatus" width="120" />
          </el-table>
          <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
            @pagination="getList" @change="paginChange"/>
        </ContentWrap>
      </el-col>
      <el-col :span="4" :xs="24">
        <div class="flex justify-between items-center ml-10px">
          <div>已选择人员：</div>
          <el-button v-if="select == 'multiple'" type="danger" size="small" @click="clearAll">全部清空</el-button>
        </div>
        <div>
          <div v-if="select == 'radio' && singleSelection && singleSelection.nickname" class="multipleCorner">
            <span>{{ singleSelection.nickname }}</span>
          </div>
          <div v-else class="multipleCorner" v-for="(item,index) in multipleSelection" :key="item.id">
            <span>{{ item.nickname }}</span>
            <Icon class="mr-5px" icon="material-symbols-light:close"  @click="deleteRow(index)"/>
          </div>

        </div>
      </el-col>
    </el-row>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="confirm">确认</el-button>
        <el-button @click="cancle">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import DeptTree from '@/views/system/user/DeptTree.vue'
import * as UserApi from '@/api/system/user'
import { ref } from 'vue'
import { number } from 'vue-types';
import { set } from 'nprogress';
import {getUserSelectPage} from "@/api/system/user";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
const props = defineProps({
  select: {
    type: String,
    default: 'radio'
  }
})
const dialogVisible = ref(false)
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数

let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: undefined,
  deptId: undefined,
  "username": undefined,
  "mobile": undefined,
  "status": undefined,
  "userDeptName": '',
  "nameOrJobNumberOrMobile": '',
  "employeeTypeCode": '',
  "deptStatus": 0,
  "userDeptId": undefined
})
/** 搜索按钮操作 */
// const handleQuery = () => {
//   queryParams.pageNo = 1
//   getList()
// }

/* 高级搜索项定义变量 */
const heightSearch = ref([
  {
    type: 'input',
    label: '所属部门',
    key: 'userDeptName',
    value:''
  },
  {
    type: 'select',
    label: '员工类型',
    key: 'employeeTypeCode',
    selectArr:  getIntDictOptions(DICT_TYPE.HR_EMPLOYTYPE),
    value:''
  }
]);
const singleParams = reactive(
  {
    type: 'input',
    label: '姓名、工号或手机号'
  }
);

/*  单个-搜索 */
const singleSearch = async (val) => {
  console.log(val)
  queryParams.nameOrJobNumberOrMobile = val;
  await getList()
}

/*  高级搜索-搜索 */
const heigthSearchValue = async (val) => {
  queryParams = {
    ...queryParams,
    ...val // 这将覆盖queryParams中与新Values中同名的属性
  };
  console.log(queryParams)
  await getList()
}
/* 重置表单 */
const resetTable = async(val) => {
  queryParams = {
    ...queryParams,
    ...val // 这将覆盖queryParams中与新Values中同名的属性
  };
  console.log(queryParams)
  await getList()
}

/** 打开弹窗 */
const open = () => {
  singleSelection.value = {
    id: 0,
    nickname: ''
  }
  multipleSelection.value = []
  queryParams.nickname = undefined
  dialogVisible.value = true
  getList()
}
defineExpose({
  open
})
/* 单选 */
interface User {
  id: number,
  nickname: string
}
const singleSelection = ref<User>({
  id: 0,
  nickname: ''
})
const handleCurrentChange = (val) => {
  singleSelection.value = val;
  console.log(singleSelection.value)
}

/* 多选 */
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val) => {
  if (!sessionStorage.getItem('multipleSelection')) {
    sessionStorage.setItem('multipleSelection', JSON.stringify(val))
    multipleSelection.value = val
  }

  console.log(multipleSelection.value)
}
const selectChange = (val, row) => {
  console.log(val, row)
  multipleSelection.value = [row]
  if (sessionStorage.getItem('multipleSelection')) {
    const sessionArr = JSON.parse(sessionStorage.getItem('multipleSelection'));
    sessionArr.push(row)
    sessionStorage.setItem('multipleSelection', JSON.stringify(sessionArr))
    multipleSelection.value = sessionArr
    // sessionStorage.setItem('multipleSelection', JSON.stringify(val))
  } 

  console.log(multipleSelection.value)
}
/* 页码改变 */
// const multipleTable = ref()
// const paginChange = (val) => {
//   const sessionArr = JSON.parse(sessionStorage.getItem('multipleSelection'));
//     nextTick(()=>{
//       multipleTable.value!.toggleRowSelection(sessionArr[0],true)
//             })
// }
const deleteRow = (index) => {
  multipleSelection.value.splice(index, 1)
  sessionStorage.setItem('multipleSelection', JSON.stringify(multipleSelection.value))
  console.log(multipleSelection.value)
}
/* 全部清空 */
const clearAll = () => {
  multipleSelection.value = []
  sessionStorage.removeItem('multipleSelection')
}
/* 关闭页面 */
const cancle = () => {
  dialogVisible.value = false
  clearAll()
}
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.userDeptId = row.id
  await getList()
}
const switchStatueChange = async (val) => {
  if (val) {
    queryParams.deptStatus = null;
  } else {
    queryParams.deptStatus = 0;
  }
  await getList()
}
/** 查询列表 */
const getList = async () => {
  try {
    const data = await UserApi.getUserSelectPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
  }
}
// 确认
const emit = defineEmits(['selectperson'])
const confirm = () => {
  if (props.select == 'multiple') {
    emit('selectperson', multipleSelection.value)
  }
  else {
    emit('selectperson', singleSelection.value)
  }
  dialogVisible.value = false
}
</script>
<style lang="scss" scoped>
.multipleCorner {
  background: #eee;
  display: inline-block;
  padding: 5px 10px;
  border-radius: 10px;
  font-size: 14px;
  margin: 5px;

  span {
    margin-right: 5px;
  }
}
</style>
